<template>
    <div>
        <headerVue title="体检套餐管理"></headerVue>

        <div class="searchData">
            <div class="bx">

                <div class="dataSearch">

                    <div class="top-box">
                        <p>数据筛选</p>
                    </div>
                    <div class="bottom-box">
                        <div class="left-box">
                            <div class="searchProject">
                                <label for="projectId">输入查询：</label>
                                <el-input v-model="projectId" placeholder="套餐ID或套餐名称" clearable id="projectId" />
                            </div>
                            <div class="suitArea">
                                <p>适用地区：</p>
                                <SelectCity @select="changeProCity" ref="sonSelectCity"></SelectCity>
                            </div>
                            <!-- 选择机构 -->
                            <div class="mechanism">
                                <p>选择机构：</p>
                                <div class="choiceMechanism">
                                    <el-select v-model="choiceMechanism" class="m-2" placeholder="全部" size="small"
                                        :clearable="true">
                                        <el-option v-for="item in options" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </div>
                            </div>
                        </div>
                        <div class="right-box">
                            <el-button type="primary" color="#0079fe" @click="searchButton">查询</el-button>
                            <el-button color="#ffffff" class="reset" @click="resetButton">重置</el-button>
                        </div>
                    </div>
                </div>
                <div class="dataShow">
                    <div class="top-button">
                        <div>
                            <addTestSetMealVue @addChange="updatePage" flagShowControl="addbutton"></addTestSetMealVue>

                        </div>
                        <div class="delManydataBox">
                            <button @click="showDeloption">删除</button>
                            <div class="isAffirm" v-show="flagIsAffirm" ref="delManydataOption">
                                <input type="button" value="已勾选数据" @click="delSelectManydata">
                                <input type="button" value="未勾选数据" @click="delNoselectData">
                            </div>
                        </div>
                        <div>
                            <button>导入</button>
                        </div>
                    </div>
                    <div class="showTable">
                        <el-table :data="tableData" :border="true" style="width: 100%" :highlight-current-row="false"
                            :cell-style="{ 'text-align': 'center', 'font-size': '12px' }" :header-cell-style="{
                                'text-align': 'center',
                                'background-color': '#f9fafc',
                                'color': '#666'
                            }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" min-width="53" />
                            <el-table-column prop="projectid" label="项目ID" min-width="157" />
                            <el-table-column prop="projectname" label="项目名称" min-width="179" />
                            <el-table-column prop="originPrice" label="原价" min-width="91" />
                            <el-table-column prop="salePeice" label="售价" min-width="89" />
                            <el-table-column prop="province" label="适用地址" min-width="223" />
                            <el-table-column label="是否启用" min-width="112">
                                <template #default="scope">
                                    {{ scope.row.isUse ? "已启用" : "未启用" }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="ordernum" label="订购数量" min-width="93" />
                            <el-table-column label="操作" min-width="183">
                                <template #default="scope">
                                    <div class="operateTable">
                                        <addTestSetMealVue @addChange="updatePage" flagShowControl="editbutton"
                                            :getDataById="scope.row.id">
                                        </addTestSetMealVue>
                                        <!-- <p>编辑</p> -->
                                        <el-popconfirm title="您确认要删除嘛?" confirm-button-text="是" cancel-button-text="否"
                                            @confirm="confirmDel(scope.row.id)">
                                            <template #reference>
                                                <p>删除</p>
                                            </template>
                                        </el-popconfirm>

                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

            </div>
        </div>
        <div class="demo-pagination-block">
            每页：
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
                :small="true" :background="true" layout="sizes, slot, prev, pager, next, jumper" :default-page-size="10"
                :total="total" :pager-count="6" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                <template #default>
                    <p>共<span>{{ pages }}</span>页/<span>{{ total }}</span>条数据</p>
                </template>
            </el-pagination>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import headerVue from '@/component/header.vue';
import SelectCity from '@/component/selectCity.vue';
import { ElNotification } from 'element-plus';
import { ElTable } from 'element-plus';
import service from "@/utils/service";
import { ElMessage, ElMessageBox } from 'element-plus';
import addTestSetMealVue from "./addTestSetMeal.vue"
import { multipleModuleTotal, multipleModuleData } from "./tools"

// 点击改变边框颜色（暂时实现不了）
// const borderColor = (e: MouseEvent) => {
//     (e.target as HTMLElement).style.borderColor = "#e9e9e9"
// }
// 搜索框的值
const projectId = ref<string>('')
// 获取省市
const sonSelectCity = ref(null)
const sonProvince = ref("")
const sonCity = ref("")
const changeProCity = (province: string, city: string) => {
    sonProvince.value = province
    sonCity.value = city


}
// 选择机构
const choiceMechanism = ref('')
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 定义搜索类型
interface ISearchType {
    _page?: number,
    _limit?: number,
    projectid?: string,
    projectname?: string,
    province?: string,
    city?: string,
    suitMechanism?: string
}


// 根据项目ID、名称查询数据
const getTableByAnySituation = () => {
    const searchKeysTotal = reactive<ISearchType>({})
    const searchKeysDataPage = reactive<ISearchType>({
        _page: currentPage.value,
        _limit: pageSize.value
    })

    if (projectId.value.length) {
        if (projectId.value.charAt(0) === "T") {
            searchKeysTotal.projectid = projectId.value
            searchKeysDataPage.projectid = projectId.value
        } else {
            searchKeysTotal.projectname = projectId.value
            searchKeysDataPage.projectname = projectId.value
        }
    }
    searchKeysTotal.province = sonProvince.value
    searchKeysDataPage.province = sonProvince.value
    searchKeysTotal.city = sonCity.value
    searchKeysDataPage.city = sonCity.value
    searchKeysTotal.suitMechanism = choiceMechanism.value
    searchKeysDataPage.suitMechanism = choiceMechanism.value

    multipleModuleTotal(searchKeysTotal).then(res => {
        total.value = res
    })
    multipleModuleData(searchKeysDataPage).then(res => {
        tableData.length = 0
        tableData.push(...res)
    })
}
getTableByAnySituation()

// 查询按钮
const searchButton = (e: MouseEvent) => {
    // Element-plus 按钮失去焦点
    let target = e.target;
    if ((target as HTMLElement).nodeName == "I" || (target as HTMLElement).nodeName == "SPAN") {
        target = (target as HTMLElement).parentNode;
    }
    (target as HTMLElement).blur();
    getTableByAnySituation()
}
// 绑定回车
document.onkeydown = (e) => {
    if (e.code === "Enter") {
        getTableByAnySituation()
    }
}

// 重置按钮
const resetButton = (e: MouseEvent) => {
    let target = e.target;
    if ((target as HTMLElement).nodeName == "I" || (target as HTMLElement).nodeName == "SPAN") {
        target = (target as HTMLElement).parentNode;
    }
    (target as HTMLElement).blur();
    projectId.value = "";
    choiceMechanism.value = "";
    (sonSelectCity.value as any).provinceValue = "";
    (sonSelectCity.value as any).cityValue = "";

}

// 表格头部样式设计

// 多选数据
const options = [
    {
        value: '美年大健康',
        label: '美年大健康',
    },
    {
        value: '平安体检',
        label: '平安体检',
    },
    {
        value: '海月体检',
        label: '海月体检',
    }
]
const flagIsAffirm = ref<boolean>(false)
// 点击删除显示删除选项
const showDeloption = (e: MouseEvent) => {
    e.stopPropagation();
    ((delManydataOption.value as unknown) as HTMLElement).style.top = `${e.offsetY}px`;
    ((delManydataOption.value as unknown) as HTMLElement).style.left = `${e.offsetX}px`;
    // 显示删除选项框
    flagIsAffirm.value = true
}
// 隐藏删除选项框
document.onclick = () => {
    flagIsAffirm.value = false
}
// 获取
const delManydataOption = ref(null)

// 删除选中多条数据
const delSelectManydata = () => {
    if (multipleSelection.length === 0) {
        ElMessageBox.alert('请先选择数据！', {
            confirmButtonText: '好的'
        }).catch(() => { })
    } else {
        ElMessageBox.confirm(
            '是否确定删除数据？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                multipleSelection.forEach(item => {
                    service({
                        url: `/testHospitals/${item.id}`,
                        method: "delete"
                    })
                })
                getTableByAnySituation()
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30px;height:30px;margin-right:5px;"/><strong>删除成功</strong>',
                })
            })
            .catch(() => {
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30x;height:30px;margin-right:5px;"/><strong>取消删除</strong>',
                })
            })
    }
}
// 删除未选中的数据
const delNoselectData = async () => {
    if (multipleSelection.length === 0) {
        ElMessageBox.alert('请先选择数据！', {
            confirmButtonText: '好的'
        }).catch(() => { })
    } else {
        // 未选中的数据(获取未选中)
        let checkedKeys = <number[]>[]
        multipleSelection.forEach(item => {
            checkedKeys.push(item.id)
        })
        let unselectedData = <number[]>[]
        tableData.forEach(item => {
            if (!checkedKeys.includes(item.id)) {
                unselectedData.push(item.id)
            }
        })
        ElMessageBox.confirm(
            '是否确定删除数据？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                unselectedData.forEach(item => {
                    service({
                        url: `/testHospitals/${item}`,
                        method: "delete"
                    })
                })

                await getTableByAnySituation()
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30x;height:30px;margin-right:5px;"/><strong>删除成功</strong>',
                })

            })
            .catch(() => {
                ElNotification({
                    title: '',
                    dangerouslyUseHTMLString: true,
                    message: '<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" style="width:30x;height:30px;margin-right:5px;"/><strong>取消删除</strong>',
                })
            })
    }
}
// 表格数据
interface ITestOption {
    projectid: string,
    projectname: string,
    originPrice: number,
    salePeice: number,
    province: string,
    city: string,
    isUse: boolean,
    ordernum?: number,
    id: number
}
const tableData = reactive<ITestOption[]>([])

// 获取表格组件
// const multipleTableRef = ref<InstanceType<typeof ElTable>>()
// 选中行的数据
const multipleSelection = reactive<ITestOption[]>([])
//  表格多选操作
const handleSelectionChange = (val: ITestOption[]) => {
    multipleSelection.length = 0
    multipleSelection.push(...val)
}
// 确认删除单行数据
const confirmDel = async (id: number) => {
    let res = await service({
        url: `/testHospitals/${id}`,
        method: "delete"
    })
    if (res.data) {
        ElMessage({
            message: "删除成功！",
            type: "success"
        })
    }
    getTableByAnySituation()
}

// 共多少页
const pages = ref(parseInt(((total.value / pageSize.value) as unknown) as string) + 1)
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
}

// getTableData()
interface IgetTableArg {
    _page?: number,
    _limit?: number,
    projectid?: string,
    projectname?: string,
    address?: string,
    mechanism?: string

}

// 监听变化发送请求
watch([currentPage, pageSize], () => {
    getTableByAnySituation()
})
const updatePage = () => {
    getTableByAnySituation()
}
</script>

<style scoped>
.searchData {
    background-color: #fff;
}

.bx {
    margin-left: 8px;
    margin-right: 18px;
}

.bx .dataSearch {
    height: 122px;
    margin-bottom: 10px;
    border: 1px solid #e9e9e9;
}

.bx .dataSearch .top-button {
    margin-left: 10px;
}

.bx .dataSearch .top-box {
    height: 50px;
    border-bottom: 1px solid #e9e9e9;
}

.bx .dataSearch .top-box p {
    color: #333;
    font-size: 14px;
    line-height: 50px;
    font-weight: bold;
    margin-left: 10px;
}

.bx .dataSearch .bottom-box {
    height: calc(122px - 50px);
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
}

.bx .dataSearch .bottom-box .left-box {
    display: flex;
}

/* 输入查询 */
.bx .dataSearch .bottom-box .searchProject {
    margin-left: 30px;
}

.bx .dataSearch .bottom-box .searchProject .el-input {
    width: 180px;
    height: 35px;
}

.bx .dataSearch .bottom-box .suitArea {
    display: flex;
    margin-left: 30px;
    align-items: center;
}

.bx .bottom-box .el-select {
    color: #333;
}

.bx .bottom-box .mechanism {
    margin-left: 20px;
    display: flex;
    align-items: center;
}

.bx .bottom-box .mechanism .choiceMechanism {
    padding: 0 2px;
    width: 180px;
    height: 35px;
    border: 1px solid #e9e9e9;
    display: flex;
    align-items: center;
}

.bx .bottom-box .right-box .el-button {
    width: 80px;
    height: 35px;
}

.bx .bottom-box .right-box .reset {
    border: 1px solid #e9e9e9;
    color: #999;
}

.bx .dataSearch .bottom-box .right-box .reset:hover {
    border: 1px solid rgb(0, 121, 254);
    color: rgb(0, 121, 254);
}

.bx .dataShow .top-button {
    display: flex;
}

.bx .dataShow .top-button>div {
    margin-left: 7px;
}

.bx .dataShow .top-button button {
    box-sizing: border-box;
    width: 81px;
    height: 30px;
    border: 1px solid #cccccc;
    background-color: #fff;
    cursor: pointer;
    font-size: 12px;
}

.bx .dataShow .top-button .delManydataBox {
    position: relative
}

.bx .dataShow .top-button .delManydataBox .isAffirm {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 89.2px;
    height: 63.8px;
    background-color: #fff;
    border: 1px solid #cccccc;
    z-index: 999;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;

}

.bx .dataShow .top-button .delManydataBox .isAffirm input {
    font-size: 12px;
    cursor: pointer;
    width: 77.6px;
    height: 23.6px;
    border: 1px solid #cccccc;
    border-radius: 2px;
}

.bx .dataShow .top-button button:hover {
    background-color: rgb(242, 242, 242);
}

.bx .dataShow .top-button {
    margin-bottom: 10px;
}

.bx .dataShow .showTable .operateTable {
    display: flex;
    justify-content: center;
    color: #1abc9c;
}

.bx .dataShow .showTable .operateTable p:hover {
    text-decoration: underline;
    cursor: pointer;
}

.bx .dataShow .showTable .operateTable p:last-child {
    margin-left: 14px;
    display: flex;
    align-items: center;
}

.demo-pagination-block {
    display: flex;
    justify-content: end;
    align-items: center;
    margin-top: 10px;
    color: #666;
    font-size: 12px;
}

.demo-pagination-block p {
    color: #666;
    font-size: 12px;
    margin-left: 5px;
}

.demo-pagination-block span {
    color: #FF3C2C;
    font-size: 12px;
}
</style>